<template>
  <div class="loginbox">
    <div>
      <h1>登录</h1>
      <el-form
        label-position="top"
        label-width="100px"
        :model="userinfo"
        style="max-width: 460px"
        :rules="rules"
        ref="formref"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userinfo.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="userinfo.password" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" round @click="login()"
            >立即登录</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import api from "../request/api";

import { reactive, ref } from "vue";

import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";

import { useRouter } from "vue-router";
const router = useRouter();

const userinfo = reactive({
  username: "admin",
  password: "admin888",
});
// rules必填
const rules = reactive<FormRules>({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
});

// 表单验证
const formref = ref();
const login = () => {
  formref.value.validate((value: any) => {
    if (value) {
      //  ElMessage.success("11111");
      //接口
      api.userlogin(userinfo).then((res: any) => {
        console.log(res);
        // 验证一致
        if (res.code == 200) {
          // 提示
          ElMessage.success(res.msg);
          // 存储本地
          sessionStorage.setItem("userinfo", JSON.stringify(res.list));
          setTimeout(() => {
            // 跳转
            router.push("/index");
          }, 500);
        } else {
          // 提示
          ElMessage.error(res.msg);
        }
      });
    } else {
      ElMessage.error("请填写完整的信息");
    }
  });
};
</script>

<style scoped>
.loginbox {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}
.loginbox > div {
  width: 460px;
  height: 500px;
  /* background: #ccc; */
}
.loginbox > div h1 {
  color: #fff;
  font-size: 30px;
  text-align: center;
}

.el-form-item__label {
  color: red;
}

.el-button.is-round {
  width: 100%;
  margin: 20px auto;
  display: block;
  height: 40px;
}
</style>